package com.itheima.controller;

import com.itheima.pojo.PageResult;
import com.itheima.pojo.Result;
import com.itheima.pojo.Student;
import com.itheima.service.StudentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/students")
public class StudentController {

    @Autowired
    private StudentService studentService;

    @GetMapping
    public Result queryStudents(
            @RequestParam(required = false) String name,
            @RequestParam(required = false) Integer degree,
            @RequestParam(required = false) Integer clazzId,
            @RequestParam(value = "page", defaultValue = "1") Integer page,
            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {

        log.info("查询学员列表: name={}, degree={}, clazzId={}, page={}, pageSize={}",
                name, degree, clazzId, page, pageSize);

        PageResult<Student> pageResult = studentService.queryStudents(name, degree, clazzId, page, pageSize);
        return Result.success(pageResult);
    }


    @PostMapping
    public Result addStudent(@RequestBody Student student) {
        log.info("添加学员: {}", student);
        studentService.addStudent(student);
        return Result.success();
    }

    @GetMapping("/{id}")
    public Result getStudentById(@PathVariable Integer id) {
        log.info("根据ID查询学员: id={}", id);
        Student student = studentService.getStudentById(id);
        return Result.success(student);
    }

    @PutMapping
    public Result updateStudent(@RequestBody Student student) {
        log.info("修改学员: {}", student);
        studentService.updateStudent(student);
        return Result.success();
    }

    @DeleteMapping("/{ids}")
    public Result deleteStudents(@PathVariable String ids) {
        log.info("批量删除学员: ids={}", ids);
        List<Integer> idList = Arrays.stream(ids.split(","))
                .map(Integer::parseInt)
                .collect(Collectors.toList());
        studentService.deleteStudents(idList);
        return Result.success();
    }

    @PutMapping("/violation/{id}/{score}")
    public Result violationHandle(@PathVariable Integer id, @PathVariable Integer score) {
        log.info("违纪处理: id={}, score={}", id, score);
        studentService.violationHandle(id, score);
        return Result.success();
    }
}
